﻿@*
    For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
    ViewData["Title"] = "编辑装箱单";
    Layout = null;
}
@Html.AntiForgeryToken()
@using Microsoft.AspNetCore.Mvc.TagHelpers
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

<link href="~/libs/scripts/layui-v2.5.6/layui/css/layui.css" rel="stylesheet" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet" />
<link href="~/Views/WarehouseManagement/PackingView.custom.css" rel="stylesheet" />
<script src="~/libs/jquery/jquery.js"></script>
<script src="~/libs/scripts/layui-v2.5.6/layui/layui.js"></script>

<style>
    .packing-form-row {
        display: flex;
        align-items: center;
        margin-bottom: 22px;
    }
    .packing-label {
        min-width: 100px;
        text-align: right;
        margin-right: 8px;
        font-weight: 500;
        font-size: 16px;
        color: #333;
    }
    .packing-required {
        color: red;
        margin-right: 4px;
        font-size: 16px;
        font-family: inherit;
    }
    .packing-input {
        width: 260px;
        margin-right: 32px;
    }
    .packing-unit {
        margin-left: 4px;
        margin-right: 24px;
        color: #888;
    }
    .packing-btn-search {
        margin-left: 4px;
        padding: 0 8px;
        height: 38px;
        line-height: 38px;
    }
    .packing-switch {
        margin-left: 8px;
        margin-right: 8px;
        vertical-align: middle;
    }
    .packing-remark-row {
        align-items: flex-start;
    }
    .packing-remark-label {
        margin-top: 8px;
    }
    .packing-remark-input {
        width: 90%;
        min-width: 400px;
        min-height: 80px;
    }
    .packing-form-actions {
        text-align: right;
        margin-top: 32px;
    }
    .input-unit-wrapper {
        position: relative;
    }
    .input-unit-suffix {
        position: absolute;
        right: 5px;
        top: 50%;
        transform: translateY(-50%);
        color: #888;
    }
    /* 弹窗美化 */
    .modal-card {
        background: #fff;
        border-radius: 14px;
        box-shadow: 0 4px 24px rgba(80, 120, 200, 0.10);
        padding: 28px 36px 18px 36px;
        margin: 0 auto;
        max-width: 1100px;
    }
    .modal-title {
        font-size: 22px;
        font-weight: 600;
        color: #3a3a3a;
        margin-bottom: 18px;
        display: flex;
        align-items: center;
        gap: 10px;
    }
    .modal-title i {
        color: #5a7cff;
        font-size: 22px;
    }
    .modal-form-grid {
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: 22px 32px;
        align-items: center;
    }
    .modal-form-group {
        display: flex;
        flex-direction: column;
    }
    .modal-label {
        font-weight: 500;
        color: #333;
        margin-bottom: 6px;
        font-size: 15px;
        display: flex;
        align-items: center;
    }
    .modal-required {
        color: #f56c6c;
        margin-right: 4px;
        font-size: 15px;
    }
    .modal-input, .modal-textarea {
        border: 1px solid #e0e3ea;
        border-radius: 6px;
        padding: 7px 12px;
        font-size: 15px;
        transition: border 0.2s;
        background: #fafbff;
    }
    .modal-input:focus, .modal-textarea:focus {
        border: 1.5px solid #5a7cff;
        background: #fff;
        outline: none;
    }
    .modal-textarea {
        min-height: 60px;
        resize: vertical;
    }
    .modal-btns {
        display: flex;
        justify-content: flex-end;
        gap: 18px;
        margin-top: 28px;
    }
    .modal-btn-primary {
        background: linear-gradient(90deg, #5a7cff 0%, #6ad1ff 100%);
        color: #fff;
        border: none;
        border-radius: 6px;
        padding: 7px 28px;
        font-size: 16px;
        font-weight: 500;
        box-shadow: 0 2px 8px rgba(90,124,255,0.08);
        transition: background 0.2s, box-shadow 0.2s;
        cursor: pointer;
    }
    .modal-btn-primary:hover {
        background: linear-gradient(90deg, #4666e5 0%, #4bbbe5 100%);
        box-shadow: 0 4px 16px rgba(90,124,255,0.13);
    }
    .modal-btn-cancel {
        background: #f3f4f8;
        color: #888;
        border: none;
        border-radius: 6px;
        padding: 7px 22px;
        font-size: 16px;
        font-weight: 500;
        cursor: pointer;
        transition: background 0.2s;
    }
    .modal-btn-cancel:hover {
        background: #e0e3ea;
    }
    .modal-qty-group {
        display: flex;
        align-items: center;
        gap: 4px;
    }
    .modal-qty-btn {
        width: 28px;
        height: 28px;
        border-radius: 4px;
        border: 1px solid #e0e3ea;
        background: #f3f4f8;
        color: #5a7cff;
        font-size: 18px;
        cursor: pointer;
        transition: background 0.2s, border 0.2s;
    }
    .modal-qty-btn:hover {
        background: #e0e3ea;
        border: 1.5px solid #5a7cff;
    }
</style>

<div class="main-container">
    <div class="page-header">
        <h1 class="page-title">
            <i class="fas fa-box"></i>
            编辑装箱单
        </h1>
    </div>
    <div class="content-card">
        <form class="layui-form packing-grid-form" id="updatePackingForm" lay-filter="updatePackingForm" autocomplete="off" style="padding: 30px 40px;">
            <div class="form-group">
                <label class="form-label">装箱单编号</label>
                <input type="text" name="PackingCode" id="packingCodeInput" placeholder="请输入装箱单编号" autocomplete="off" class="form-input" required lay-verify="required" lay-reqtext="装箱单编号不能为空" readonly>
                <input type="checkbox" name="AutoCode" id="autoGeneratePackingCode" lay-skin="switch" lay-filter="autoGeneratePackingCode" lay-text="自动生成|手动输入" style="margin-top:8px;" disabled>
            </div>
            <div class="form-group">
                <label class="form-label">装箱日期 <span style="color:red;">*</span></label>
                <input type="text" name="PackingDate" id="PackingDate" placeholder="请选择装箱日期" autocomplete="off" class="form-input" readonly required lay-verify="required" lay-reqtext="装箱日期不能为空">
            </div>
            <div class="form-group">
                <label class="form-label">销售订单编号</label>
                <input type="text" name="SaleOrderCode" placeholder="请输入销售订单编号" autocomplete="off" class="form-input" required lay-verify="required" lay-reqtext="销售订单编号不能为空">
            </div>
            <div class="form-group">
                <label class="form-label">客户编码</label>
                <div style="display: flex; align-items: center;">
                    <input type="text" name="CustomerCode" id="customerCodeInput" placeholder="请输入客户编码" autocomplete="off" class="form-input" required lay-verify="required" lay-reqtext="客户编码不能为空" readonly>
                    <button type="button" class="btn btn-secondary" id="selectCustomerBtn" style="margin-left:6px;"><i class="fas fa-search"></i></button>
                </div>
            </div>
            <div class="form-group">
                <label class="form-label">客户名称</label>
                <input type="text" name="CustomerName" id="customerNameInput" placeholder="请输入客户名称" autocomplete="off" class="form-input" required lay-verify="required" lay-reqtext="客户名称不能为空" readonly>
            </div>
            <div class="form-group">
                <label class="form-label">发票编号</label>
                <input type="text" name="InvoiceCode" placeholder="请输入发票编号" autocomplete="off" class="form-input" required lay-verify="required" lay-reqtext="发票编号不能为空">
            </div>
            <div class="form-group">
                <label class="form-label">箱长度</label>
                <div class="input-unit-wrapper">
                    <input type="text" name="PackingLength" placeholder="请输入箱长度" autocomplete="off" class="form-input" required lay-verify="required|number" lay-reqtext="箱长度不能为空">
                    <span class="input-unit-suffix">cm</span>
                </div>
            </div>
            <div class="form-group">
                <label class="form-label">箱宽度</label>
                <div class="input-unit-wrapper">
                    <input type="text" name="PackingWidth" placeholder="请输入箱宽度" autocomplete="off" class="form-input" required lay-verify="required|number" lay-reqtext="箱宽度不能为空">
                    <span class="input-unit-suffix">cm</span>
                </div>
            </div>
            <div class="form-group">
                <label class="form-label">箱高度</label>
                <div class="input-unit-wrapper">
                    <input type="text" name="PackingHeight" placeholder="请输入箱高度" autocomplete="off" class="form-input" required lay-verify="required|number" lay-reqtext="箱高度不能为空">
                    <span class="input-unit-suffix">cm</span>
                </div>
            </div>
            <div class="form-group">
                <label class="form-label">净重</label>
                <div class="input-unit-wrapper">
                    <input type="text" name="NetWeight" placeholder="请输入净重" autocomplete="off" class="form-input" required lay-verify="required|number" lay-reqtext="净重不能为空">
                    <span class="input-unit-suffix">kg</span>
                </div>
            </div>
            <div class="form-group">
                <label class="form-label">毛重</label>
                <div class="input-unit-wrapper">
                    <input type="text" name="GrossWeight" placeholder="请输入毛重" autocomplete="off" class="form-input" required lay-verify="required|number" lay-reqtext="毛重不能为空">
                    <span class="input-unit-suffix">kg</span>
                </div>
            </div>
            <div class="form-group">
                <label class="form-label">检查员名称</label>
                <input type="text" name="Inspector" placeholder="请输入检查员名称" autocomplete="off" class="form-input" required lay-verify="required" lay-reqtext="检查员名称不能为空">
            </div>
            <div class="form-group" style="grid-column: 1 / -1;">
                <label class="form-label">备注</label>
                <textarea name="Remark" placeholder="请输入内容" class="form-input" style="min-height: 80px;"></textarea>
            </div>
            <div class="btn-group" style="margin-top: 32px; justify-content: flex-end; grid-column: 1 / -1;">
                <button class="btn btn-primary" lay-submit lay-filter="updatePacking"><i class="fas fa-save"></i> 保存</button>
                <button type="button" class="btn btn-secondary" id="btnCancel"><i class="fas fa-times"></i> 取消</button>
            </div>
        </form>
    </div>
    <!-- 下半部分：选项卡 -->
    <div class="content-card" style="margin-top: 24px;">
        <div class="layui-tab" lay-filter="packingTabs">
            <ul class="layui-tab-title">
                <li class="layui-this">子箱</li>
                <li>装箱清单</li>
            </ul>
            <div class="layui-tab-content">
                <div class="layui-tab-item layui-show">
                    <div style="padding: 32px; color: #bbb; text-align: center;">子箱功能开发中...</div>
                </div>
                <div class="layui-tab-item">
                    <div class="toolbar" style="margin-bottom: 12px;">
                        <button class="btn btn-primary" id="btnAddDetail"><i class="fas fa-plus"></i> 新增</button>
                        <button class="btn btn-danger" id="btnDeleteDetail"><i class="fas fa-trash"></i> 删除</button>
                    </div>
                    <table id="packingDetailsTable" lay-filter="packingDetailsTable"></table>
                </div>
            </div>
        </div>
    </div>
</div>

<script type="text/html" id="customerSelectDialog">
    <div style="padding:20px;">
        <form class="layui-form" id="customerSearchForm" style="margin-bottom:10px;">
            <input type="text" name="CustomerCode" placeholder="客户编码" class="layui-input" style="width:150px;display:inline-block;">
            <input type="text" name="CustomerName" placeholder="客户名称" class="layui-input" style="width:150px;display:inline-block;">
            <button class="layui-btn" lay-submit lay-filter="customerSearch">搜索</button>
            <button type="reset" class="layui-btn layui-btn-primary">重置</button>
        </form>
        <table class="layui-hide" id="customerTable" lay-filter="customerTable"></table>
        <div style="text-align:right;margin-top:10px;">
            <button class="layui-btn" id="customerSelectOk">确定</button>
            <button class="layui-btn layui-btn-primary" onclick="layer.closeAll();">取消</button>
        </div>
    </div>
</script>

<!-- 明细操作列模板 -->
<script type="text/html" id="detailOperationBar">
    <div style="display: flex; flex-direction: column; align-items: center; gap: 2px;">
        <a lay-event="edit" style="color:#409EFF;font-size:13px;line-height:16px;cursor:pointer;">
            <i class="fas fa-edit"></i> 修改
        </a>
        <a lay-event="delete" style="color:#F56C6C;font-size:13px;line-height:16px;cursor:pointer;">
            <i class="fas fa-trash"></i> 删除
        </a>
    </div>
</script>

<!-- 新增装箱明细弹窗模板 -->
<script type="text/html" id="addPackingDetailDialog">
    <div class="modal-card">
        <div class="modal-title">
            <i class="fas fa-box-open"></i> <span id="packingDetailDialogTitle"></span>
        </div>
        <form class="layui-form" lay-filter="addPackingDetailForm" autocomplete="off">
            <div class="modal-form-grid">
                <div class="modal-form-group">
                    <label class="modal-label">生产工单编号</label>
                    <div style="display:flex;align-items:center;gap:6px;">
                        <input type="text" name="ProductionWorkOrderNo" placeholder="请输入生产工单编号" autocomplete="off" class="modal-input" style="flex:1;">
                        <button type="button" class="layui-btn layui-btn-primary layui-btn-xs" style="margin-left:0;"><i class="layui-icon layui-icon-search"></i></button>
                    </div>
                </div>
                <div class="modal-form-group">
                    <label class="modal-label">批次号</label>
                    <input type="text" name="BatchNo" autocomplete="off" class="modal-input">
                </div>
                <div class="modal-form-group">
                    <label class="modal-label">装箱数量 <span class="modal-required">*</span></label>
                    <div class="modal-qty-group">
                        <button type="button" class="modal-qty-btn" id="btnMinusQty">-</button>
                        <input type="number" name="PackingQuantity" value="0" min="0" class="modal-input" style="width:80px;text-align:center;">
                        <button type="button" class="modal-qty-btn" id="btnAddQty">+</button>
                    </div>
                </div>
                <div class="modal-form-group">
                    <label class="modal-label">产品物料编码</label>
                    <input type="text" name="ProductMaterialCode" autocomplete="off" class="modal-input">
                </div>
                <div class="modal-form-group">
                    <label class="modal-label">产品物料名称</label>
                    <input type="text" name="ProductMaterialName" autocomplete="off" class="modal-input">
                </div>
                <div class="modal-form-group">
                    <label class="modal-label">单位</label>
                    <input type="text" name="Unit" autocomplete="off" class="modal-input">
                </div>
                <div class="modal-form-group">
                    <label class="modal-label">规格型号</label>
                    <input type="text" name="Specification" autocomplete="off" class="modal-input">
                </div>
                <div class="modal-form-group" style="grid-column: 1 / -1;">
                    <label class="modal-label">备注</label>
                    <textarea name="Remarks" placeholder="请输入内容" class="modal-textarea"></textarea>
                </div>
            </div>
            <input type="hidden" name="PackingCode" id="addDetailPackingCode" />
            <div class="modal-btns">
                <button type="button" class="modal-btn-cancel" onclick="layer.closeAll();">取消</button>
                <button class="modal-btn-primary" lay-submit lay-filter="addOrEditPackingDetail">确定</button>
            </div>
        </form>
    </div>
</script>

<!-- 生产工单选择弹窗模板 -->
<script type="text/html" id="selectProductionOrderDialog">
    <div style="padding: 16px 24px 0 24px;">
        <table id="productionOrderTable" lay-filter="productionOrderTable"></table>
        <div style="text-align:right;margin:18px 0 8px 0;">
            <button class="layui-btn layui-btn-primary" id="btnCancelSelectProduction">取消</button>
            <button class="layui-btn" id="btnConfirmSelectProduction">确定</button>
        </div>
    </div>
</script>

<script>
layui.use(['form', 'laydate', 'table', 'layer', 'element'], function(){
    var form = layui.form,
        laydate = layui.laydate,
        table = layui.table,
        layer = layui.layer,
        element = layui.element,
        $ = layui.jquery;

    // 获取url参数id
    function getQueryString(name) {
        var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return decodeURIComponent(r[2]);
        return null;
    }
    var id = getQueryString('id');

    // 装箱日期选择
    laydate.render({
        elem: '#PackingDate',
        type: 'date'
    });

    // 加载数据并回显
    if(id){
        $.ajax({
            url: '/WarehouseManagement/GetPackingById?id=' + id,
            type: 'GET',
            success: function(res){
                if(res.success && res.data){
                    var d = res.data;
                    // 回显表单
                    form.val('updatePackingForm', {
                        'PackingCode': d.packingCode,
                        'PackingDate': d.packingDate ? d.packingDate.split('T')[0] : '',
                        'SaleOrderCode': d.saleOrderCode,
                        'InvoiceCode': d.invoiceCode,
                        'CustomerCode': d.customerCode,
                        'CustomerName': d.customerName,
                        'PackingLength': d.packingLength,
                        'PackingWidth': d.packingWidth,
                        'PackingHeight': d.packingHeight,
                        'PackingSize': d.packingSize,
                        'NetWeight': d.netWeight,
                        'GrossWeight': d.grossWeight,
                        'UnitWeight': d.unitWeight,
                        'Inspector': d.inspector,
                        'Remark': d.remark
                    });
                    // 只有此处渲染明细表格，PackingCode已回显
                    table.render({
                        elem: '#packingDetailsTable',
                        url: '/WarehouseManagement/QueryPackingDetailsModel',
                        method: 'post',
                        page: true,
                        limit: 10,
                        where: { PackingCode: d.packingCode },
                        cols: [[
                            {type: 'checkbox', fixed: 'left'},
                            {field: 'productMaterialCode', title: '产品物料编码'},
                            {field: 'productMaterialName', title: '产品物料名称'},
                            {field: 'specification', title: '规格型号'},
                            {field: 'unit', title: '单位'},
                            {field: 'packingQuantity', title: '装箱数量'},
                            {field: 'productionWorkOrderNo', title: '生产工单编号'},
                            {field: 'batchNo', title: '批次号'},
                            {title: '操作', toolbar: '#detailOperationBar', width: 100, fixed: 'right'}
                        ]]
                    });
                }else{
                    layer.msg('数据加载失败', {icon:2});
                }
            },
            error: function(){
                layer.msg('请求失败', {icon:2});
            }
        });
    }

    // 取消按钮
    $('#btnCancel').on('click', function(){
        window.history.back();
    });

    // 表单提交
    form.on('submit(updatePacking)', function(data){
        var postData = data.field;
        postData.Id = id;
        $.ajax({
            url: '/WarehouseManagement/UpdatePacking',
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(postData),
            headers: {
                'RequestVerificationToken': $('input[name="__RequestVerificationToken"]').val()
            },
            success: function(res){
                if(res.success){
                    layer.msg('保存成功', {icon: 1}, function(){
                        window.location.href = '/WarehouseManagement/PackingView';
                    });
                }else{
                    layer.msg(res.message || '保存失败', {icon: 2});
                }
            },
            error: function(){
                layer.msg('请求失败，请重试', {icon: 2});
            }
        });
        return false;
    });

    // 客户选择弹窗
    $('#selectCustomerBtn').on('click', function(){
        layer.open({
            type: 1,
            title: '客户选择',
            area: ['900px', '500px'],
            content: $('#customerSelectDialog').html(),
            success: function(layero, index){
                var tableIns = layui.table.render({
                    elem: '#customerTable',
                    url: '/Customer/ShowCustomer',
                    method: 'get',
                    page: true,
                    request: {
                        pageName: 'pageIndex',
                        limitName: 'pageSize'
                    },
                    cols: [[
                        {type:'radio', fixed: 'left', width: 50},
                        {field:'customerCode', title:'客户编码', width: 120},
                        {field:'customerName', title:'客户名称', width: 120},
                        {field:'customerShortName', title:'客户简称', width: 120},
                        {field:'customerType', title:'客户类型', width: 120},
                        {field:'customerPhone', title:'客户电话', width: 150},
                        {field:'contact', title:'联系人', width: 120},
                        {field:'contactPhone', title:'联系人电话', width: 120}
                    ]]
                });
                // 搜索
                layui.form.on('submit(customerSearch)', function(data){
                    layui.table.reload('customerTable', {
                        where: data.field,
                        page: {curr: 1}
                    });
                    return false;
                });
                // 确定按钮
                layero.find('#customerSelectOk').on('click', function(){
                    var checked = layui.table.checkStatus('customerTable').data[0];
                    if(!checked){
                        layer.msg('请选择客户');
                        return;
                    }
                    $('#customerCodeInput').val(checked.customerCode);
                    $('#customerNameInput').val(checked.customerName);
                    layer.closeAll();
                });
            }
        });
    });

    // 新增明细
    $('#btnAddDetail').on('click', function(){
        var packingCode = $('#packingCodeInput').val();
        layer.open({
            type: 1,
            title: '添加装箱明细',
            area: ['1100px', '520px'],
            offset: '40px',
            btn: ['确定', '取消'],
            content: $('#addPackingDetailDialog').html(),
            success: function(layero, index){
                var formElem = layero.find('form');
                layui.form.render();
                // 设置标题
                layero.find('#packingDetailDialogTitle').text('新增装箱明细');
                // 回显PackingCode
                formElem.find('input[name="PackingCode"]').val(packingCode);
                // 数量加减
                var qtyInput = formElem.find('input[name="PackingQuantity"]');
                formElem.find('#btnMinusQty').on('click', function(){
                    var v = parseInt(qtyInput.val()) || 0;
                    if(v > 0) qtyInput.val(v-1);
                });
                formElem.find('#btnAddQty').on('click', function(){
                    var v = parseInt(qtyInput.val()) || 0;
                    qtyInput.val(v+1);
                });
                // 放大镜弹窗
                formElem.find('button:has(.layui-icon-search)').on('click', function(){
                    var prodLayerIndex = layer.open({
                        type: 1,
                        title: '选择生产工单',
                        area: ['1200px', '700px'],
                        offset: '40px',
                        content: $('#selectProductionOrderDialog').html(),
                        success: function(prodLayero, prodIndex){
                            var selectedRow = null;
                            layui.table.render({
                                elem: prodLayero.find('#productionOrderTable'),
                                url: '/Prouduction/ShowProdction',
                                method: 'get',
                                request: { pageName: 'pageIndex', limitName: 'pageSize' },
                                page: true,
                                limit: 10,
                                height: 520,
                                cols: [[
                                    {type: 'radio', fixed: 'left'},
                                    {field: 'orderCode', title: '工单编码'},
                                    {field: 'orderName', title: '工单名称'},
                                    {field: 'sourceType', title: '工单来源'},
                                    {field: 'orderNumber', title: '订单编号'},
                                    {field: 'productionCode', title: '产品物料编码'},
                                    {field: 'productionName', title: '产品物料名称'},
                                    {field: 'specifications', title: '规格型号'},
                                    {field: 'unit', title: '单位'},
                                    {field: 'orderCount', title: '工单数量'},
                                    {field: 'customerCode', title: '客户编码'}
                                ]],
                                done: function(){
                                    prodLayero.find('tr').off('click').on('click', function(){
                                        prodLayero.find('tr').removeClass('layui-table-click');
                                        $(this).addClass('layui-table-click');
                                    });
                                }
                            });
                            // 监听单选
                            layui.table.on('radio(productionOrderTable)', function(obj){
                                selectedRow = obj.data;
                            });
                            // 确定按钮
                            prodLayero.find('#btnConfirmSelectProduction').on('click', function(){
                                if(!selectedRow){
                                    layer.msg('请选择一条工单');
                                    return;
                                }
                                // 回显到主表单
                                formElem.find('input[name="ProductionWorkOrderNo"]').val(selectedRow.orderCode || '');
                                formElem.find('input[name="ProductMaterialCode"]').val(selectedRow.productionCode || '');
                                formElem.find('input[name="ProductMaterialName"]').val(selectedRow.productionName || '');
                                formElem.find('input[name="Unit"]').val(selectedRow.unit || '');
                                layer.close(prodLayerIndex);
                            });
                            // 取消按钮
                            prodLayero.find('#btnCancelSelectProduction').on('click', function(){
                                layer.close(prodLayerIndex);
                            });
                        }
                    });
                });
            },
            yes: function(index, layero){
                var formElem = layero.find('form');
                var data = {};
                formElem.serializeArray().forEach(function(item){ data[item.name] = item.value; });
                if(!data.PackingQuantity || isNaN(data.PackingQuantity) || parseInt(data.PackingQuantity) <= 0){
                    layer.msg('装箱数量必须大于0');
                    return;
                }
                $.ajax({
                    url: '/WarehouseManagement/AddPackingDetailsModelS',
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify(data),
                    success: function(res){
                        if(res.success){
                            layer.msg('添加成功', {icon: 1});
                            table.reload('packingDetailsTable', { where: { PackingCode: $('#packingCodeInput').val() } });
                            layer.close(index);
                        }else{
                            layer.msg(res.message || '添加失败', {icon: 2});
                        }
                    },
                    error: function(){
                        layer.msg('请求失败，请重试', {icon: 2});
                    }
                });
            }
        });
    });
    // 批量删除明细
    $('#btnDeleteDetail').on('click', function(){
        var checkStatus = table.checkStatus('packingDetailsTable');
        var data = checkStatus.data;
        if(data.length === 0){
            layer.msg('请选择要删除的明细', {icon: 2});
            return;
        }
        layer.confirm('确定要删除选中的 ' + data.length + ' 条明细吗？', {
            icon: 3,
            title: '确认删除'
        }, function(index){
            var ids = data.map(function(item){ return item.id; });
            $.ajax({
                url: '/WarehouseManagement/BatchDeletePackingDetailsModel',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(ids),
                success: function(res){
                    if(res.success){
                        layer.msg('删除成功', {icon: 1});
                        table.reload('packingDetailsTable', { where: { PackingCode: $('#packingCodeInput').val() } });
                    } else {
                        layer.msg(res.message || '删除失败', {icon: 2});
                    }
                },
                error: function(){
                    layer.msg('操作失败，请重试', {icon: 2});
                }
            });
            layer.close(index);
        });
    });

    // 编辑明细
    table.on('tool(packingDetailsTable)', function(obj){
        if(obj.event === 'edit'){
            var rowData = obj.data;
            layer.open({
                type: 1,
                title: '编辑装箱明细',
                area: ['1100px', '520px'],
                offset: '40px',
                btn: ['确定', '取消'],
                content: $('#addPackingDetailDialog').html(),
                success: function(layero, index){
                    var formElem = layero.find('form');
                    layui.form.render();
                    // 设置标题
                    layero.find('#packingDetailDialogTitle').text('编辑装箱明细');
                    // 回显数据
                    formElem.find('input[name="PackingCode"]').val(rowData.packingCode || '');
                    formElem.find('input[name="ProductionWorkOrderNo"]').val(rowData.productionWorkOrderNo || '');
                    formElem.find('input[name="BatchNo"]').val(rowData.batchNo || '');
                    formElem.find('input[name="PackingQuantity"]').val(rowData.packingQuantity || '');
                    formElem.find('input[name="ProductMaterialCode"]').val(rowData.productMaterialCode || '');
                    formElem.find('input[name="ProductMaterialName"]').val(rowData.productMaterialName || '');
                    formElem.find('input[name="Unit"]').val(rowData.unit || '');
                    formElem.find('input[name="Specification"]').val(rowData.specification || '');
                    formElem.find('textarea[name="Remarks"]').val(rowData.remarks || '');
                    // 数量加减
                    var qtyInput = formElem.find('input[name="PackingQuantity"]');
                    formElem.find('#btnMinusQty').on('click', function(){
                        var v = parseInt(qtyInput.val()) || 0;
                        if(v > 0) qtyInput.val(v-1);
                    });
                    formElem.find('#btnAddQty').on('click', function(){
                        var v = parseInt(qtyInput.val()) || 0;
                        qtyInput.val(v+1);
                    });
                    // 放大镜弹窗
                    formElem.find('button:has(.layui-icon-search)').on('click', function(){
                        var prodLayerIndex = layer.open({
                            type: 1,
                            title: '选择生产工单',
                            area: ['1200px', '700px'],
                            offset: '40px',
                            content: $('#selectProductionOrderDialog').html(),
                            success: function(prodLayero, prodIndex){
                                var selectedRow = null;
                                layui.table.render({
                                    elem: prodLayero.find('#productionOrderTable'),
                                    url: '/Prouduction/ShowProdction',
                                    method: 'get',
                                    request: { pageName: 'pageIndex', limitName: 'pageSize' },
                                    page: true,
                                    limit: 10,
                                    height: 520,
                                    cols: [[
                                        {type: 'radio', fixed: 'left'},
                                        {field: 'orderCode', title: '工单编码'},
                                        {field: 'orderName', title: '工单名称'},
                                        {field: 'sourceType', title: '工单来源'},
                                        {field: 'orderNumber', title: '订单编号'},
                                        {field: 'productionCode', title: '产品物料编码'},
                                        {field: 'productionName', title: '产品物料名称'},
                                        {field: 'specifications', title: '规格型号'},
                                        {field: 'unit', title: '单位'},
                                        {field: 'orderCount', title: '工单数量'},
                                        {field: 'customerCode', title: '客户编码'}
                                    ]],
                                    done: function(){
                                        prodLayero.find('tr').off('click').on('click', function(){
                                            prodLayero.find('tr').removeClass('layui-table-click');
                                            $(this).addClass('layui-table-click');
                                        });
                                    }
                                });
                                // 监听单选
                                layui.table.on('radio(productionOrderTable)', function(obj){
                                    selectedRow = obj.data;
                                });
                                // 确定按钮
                                prodLayero.find('#btnConfirmSelectProduction').on('click', function(){
                                    if(!selectedRow){
                                        layer.msg('请选择一条工单');
                                        return;
                                    }
                                    // 回显到主表单
                                    formElem.find('input[name="ProductionWorkOrderNo"]').val(selectedRow.orderCode || '');
                                    formElem.find('input[name="ProductMaterialCode"]').val(selectedRow.productionCode || '');
                                    formElem.find('input[name="ProductMaterialName"]').val(selectedRow.productionName || '');
                                    formElem.find('input[name="Unit"]').val(selectedRow.unit || '');
                                    layer.close(prodLayerIndex);
                                });
                                // 取消按钮
                                prodLayero.find('#btnCancelSelectProduction').on('click', function(){
                                    layer.close(prodLayerIndex);
                                });
                            }
                        });
                    });
                },
                yes: function(index, layero){
                    var formElem = layero.find('form');
                    var data = {};
                    formElem.serializeArray().forEach(function(item){ data[item.name] = item.value; });
                    data.Id = rowData.id; // 传递主键ID用于更新
                    if(!data.PackingQuantity || isNaN(data.PackingQuantity) || parseInt(data.PackingQuantity) <= 0){
                        layer.msg('装箱数量必须大于0');
                        return;
                    }
                    $.ajax({
                        url: '/WarehouseManagement/UpdatePackingDetailsModel',
                        type: 'POST',
                        contentType: 'application/json',
                        data: JSON.stringify(data),
                        success: function(res){
                            if(res.success){
                                layer.msg('修改成功', {icon: 1});
                                table.reload('packingDetailsTable', { where: { PackingCode: $('#packingCodeInput').val() } });
                                layer.close(index);
                            }else{
                                layer.msg(res.message || '修改失败', {icon: 2});
                            }
                        },
                        error: function(){
                            layer.msg('请求失败，请重试', {icon: 2});
                        }
                    });
                }
            });
        }
        if(obj.event === 'delete'){
            var rowData = obj.data;
            layer.confirm('确定要删除该明细吗？', {icon: 3, title: '确认删除'}, function(index){
                $.ajax({
                    url: '/WarehouseManagement/BatchDeletePackingDetailsModel',
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify([rowData.id]),
                    success: function(res){
                        if(res.success){
                            layer.msg('删除成功', {icon: 1});
                            table.reload('packingDetailsTable', { where: { PackingCode: $('#packingCodeInput').val() } });
                        } else {
                            layer.msg(res.message || '删除失败', {icon: 2});
                        }
                    },
                    error: function(){
                        layer.msg('操作失败，请重试', {icon: 2});
                    }
                });
                layer.close(index);
            });
        }
    });
});
</script>
